#include "adc.h"

void Adc_Init(void){
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
    RCC_ADCCLKConfig(RCC_PCLK2_Div6);//6分频

    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN ;//选择模拟输入模式即AIN
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB,&GPIO_InitStructure);

    ADC_RegularChannelConfig(ADC1,ADC_Channel_0,1,ADC_SampleTime_55Cycles5);

    ADC_InitTypeDef ADC_InitStructure;
    ADC_InitStructure.ADC_Mode= ADC_Mode_Independent; //独立模式
    ADC_InitStructure.ADC_DataAlign= ADC_DataAlign_Right; //数据对齐：右对齐
    ADC_InitStructure.ADC_ExternalTrigConv= ADC_ExternalTrigConv_None; //软件触发
    ADC_InitStructure.ADC_ContinuousConvMode= DISABLE; // 单次转换
    ADC_InitStructure.ADC_ScanConvMode= DISABLE; //转换模式：非扫描
    ADC_InitStructure.ADC_NbrOfChannel= 1; //通道数目：
    ADC_Init(ADC1,&ADC_InitStructure);

    ADC_Cmd(ADC1,ENABLE);

    ADC_ResetCalibration(ADC1); //校准
    while (ADC_GetCalibrationStatus(ADC1) == SET);
    ADC_StartCalibration(ADC1);
    while (ADC_GetCalibrationStatus(ADC1) == SET);
}

uint16_t ADC_GetValue(void){
    ADC_SoftwareStartConvCmd(ADC1,ENABLE); //软件触发,ADC开始转换
    while (ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC) == RESET); //ADC转换需要一定时间
    return ADC_GetConversionValue(ADC1); //获取转换值
}

